package com.example.aigc_education.config;


import com.example.aigc_education.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Aspect
@Component
public class LoggingAOPConfig {

//    @Pointcut("execution(* com.example.aigc_education.controller.*.*(..))")
//    public void setLog() {
//    }

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)||@within(org.springframework.stereotype.Controller)")
    public void cutController() {
    }


//    @Around("setLog()")
//    public Object requestLog(ProceedingJoinPoint joinPoint) throws Throwable {
//        // 日志格式 类-方法 request args {}， args
//        log.info("{}-{} request args {}", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName(), joinPoint.getArgs());
//        Object result = joinPoint.proceed();
//        log.info("{}-{} response {}", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName(), result);
//        return result;
//    }

    @Before("cutController()")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url = request.getRequestURL().toString();
        List<Object> list = new ArrayList<>();
        for (Object arg : joinPoint.getArgs()) {
            if (arg instanceof MultipartFile || arg instanceof HttpServletRequest ||
            arg instanceof HttpServletResponse || arg instanceof BindingResult) {
                continue;
            }
            list.add(arg);
        }
        log.info("请求url:{}, params:{}", url, JsonUtils.toJson(list));
    }

    @AfterReturning(returning = "response", pointcut = "cutController()")
    public void doAfterReturning(Object response) {
        if (response != null) {
            log.info("请求返回result:{}", JsonUtils.toJson(response));
        }
    }
}
